import re
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib
import pytz
# plt.ion()
# 设置字体
matplotlib.rcParams['font.sans-serif'] = ['SimHei']  # 黑体字
matplotlib.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题


# 创建绘图
def data_show(filepath, stage_list, hr_df, detail_df,rri_df,fit_df,kuaice_df):



    if kuaice_df.empty:
        print('')
    else:
        # 获取当前的时间戳和心率值
        initial_timestamp = kuaice_df['timestamp'].iloc[0]
        initial_hr_value = kuaice_df['HR'].iloc[0]

        # 创建新的时间戳（自增120个点，每个点间隔1秒）
        time_increment = pd.Timedelta(seconds=1)  # 每个点间隔1秒
        new_timestamps = [initial_timestamp + i * time_increment for i in range(120)]

        # 创建新的 DataFrame
        kuaice_df = pd.DataFrame({
            'timestamp': new_timestamps,
            'HR': [initial_hr_value] * 120  # 保持心率值与第一个点相同
        })

    # 生成假设的心率和RR数据


    # 创建不同长度的时间戳


    # 创建子图
    fig, (ax_hr, ax_rr) = plt.subplots(nrows=2, ncols=1, figsize=(20, 15), sharex=True)

    # 定义阶段背景颜色
    phase_colors = ['lightblue', 'lightgreen', 'lightyellow', 'lightcoral', 'lightsalmon']

    # 绘制心率数据的背景阶段
    for i, (stage, start, end) in enumerate(stage_list):
        ax_hr.axvspan(pd.to_datetime(start, unit='s'), pd.to_datetime(end, unit='s'),
                      color=phase_colors[i % len(phase_colors)], alpha=0.3, label=f'Stage {i + 1}')
        mid_point = pd.to_datetime(start, unit='s') + (
                    pd.to_datetime(end, unit='s') - pd.to_datetime(start, unit='s')) / 2
        ax_hr.text(mid_point, ax_hr.get_ylim()[1] * 0.8, f'阶段 {stage}', ha='center', va='center', fontsize=20,
                   color='black')

    # 绘制心率数据
    ax_hr.plot(hr_df['timestamp'], hr_df['HR'], label=f'polar({len(hr_df)} points)', color='red')
    ax_hr.plot(detail_df['timestamp'], detail_df['心率'], label=f'华为({len(detail_df)} points)',
               color='green')
    ax_hr.plot(fit_df['timestamp'], fit_df['HR'], label=f'竞品({len(fit_df)} points)',
               color='blue')
    ax_hr.plot(kuaice_df['timestamp'], kuaice_df['HR'], label=f'健康快测 ({len(kuaice_df)} points)',
               color='purple')

    # 设置心率子图的 Y 轴范围
    ax_hr.set_ylim(0, 200)

    # 设置心率子图的标题和标签
    ax_hr.set_title(filepath)
    ax_hr.set_ylabel('Heart Rate')
    ax_hr.legend(loc='upper right')

    # 绘制RR数据
    ax_rr.plot(hr_df['timestamp'], hr_df['rr1'], label=f'polar的RR1)', color='orange',
               linestyle='--')
    ax_rr.plot(rri_df['timestamp'], rri_df['value'], label=f'huaweid RR)', color='brown',
               linestyle='--')

    # 设置RR子图的标题和标签
    ax_rr.set_title('RR Interval Data')
    ax_rr.set_xlabel('Time')
    ax_rr.set_ylabel('RR Interval')
    ax_rr.legend(loc='upper right')

    # 显示图像
    # plt.tight_layout()
    # plt.savefig(f'D:\\学习&科研\\华为手表项目\\华为数据\\规律跑者\\check_data\\img\\'+filepath + '.png')
    
    # plt.show()
    # plt.pause(1)
    
   
    # datetime_re=re.compile(r'(\d{4})-\d{1,2}-\d{1,2}-(\d{4}-\d{2}-\d{2}-\d{2})')
    # date_match = datetime_re.search(filepath)
    # if date_match is None: 
    #     date_stat='error'
    # else:
    #     date_stat=f"{date_match.group(1)}-{date_match.group(2)}"
    if len(kuaice_df)==120 and len(fit_df)==0 and len(detail_df)==0 and len(hr_df)!=0 and len(rri_df)!=0:
        date_stat="静息"
    elif len(hr_df)!=0 and len(detail_df)!=0 and len(fit_df)!=0 and len(fit_df)!=0:
        date_stat="运动"
    else:
        date_stat="未知"
    

# 调用函数
# data_show('data_filepath', stage_list, hr_df, detail_df)
    return date_stat,filepath,len(hr_df), len(detail_df), len(rri_df), len(fit_df), len(kuaice_df)